/* eslint-disable no-unused-expressions */
/* eslint-disable global-require */
import ElEditable from '@components/el-editable';
import TableUpload from '~/modules/table-upload';
import {
  orderCommonFindOrderStatus, // 医院订单管理-订单状态集
  orderCommonQueryOrderInfo, // 医院订单管理-订单基本信息
  commerceGetOrderFlow,
  stockBatchList,
  orderProductList,
  orderPageList,
  getOrderDeliverList,
  findPaymentByOrderId,
  getOrderDeliverDetailList,
  getOrderLogistics,
  orderCancelProductList,
  orderGetAppendInfo,
  returnStatus,
  findProductSnInfo
} from '@api/m_mall_web_v1.js';
import {
  COLUMNS,
  DELIVERY_ORDER_COLUMNS,
  RECEIVE_COLUMNS,
  RECEIVE_COORDINATION,
  SHIPPING_INFORMATION,
  PAY_INFO,
  FILE_COLUMNS,
  CANCEL_COLUMNS,
  ACCESSORIES_COLUMNS,
  STOCK_TYPE
} from './index.const';
// eslint-disable-next-line import/extensions
import step from '~/modules/step';

export default {
  components: {
    ElEditable,
    step,
    TableUpload
  },
  inject: ['apiMMallWeb'],
  data() {
    return {
      // text: "(去应付账单管理支付)",
      // timeOut: '00:00:00',
      // showTimeOut: true,
      activeStatus: 1,
      STEP_LIST: [
        {
          // eslint-disable-next-line global-require
          finishSrc: require('@assets/img/dingdantijiao-icon@2x.png'),
          waitSrc: require('@assets/img/dingdantijiao-icon@2x.png')
        },
        {
          finishSrc: require('@assets/img/yifahuo-icon@2x.png'),
          waitSrc: require('@assets/img/yifahuo-icon1@2x.png')
        },
        {
          finishSrc: require('@assets/img/shouhuo-icon@2x.png'),
          waitSrc: require('@assets/img/shouhuo-icon1@2x.png')
        },
        {
          finishSrc: require('@assets/img/yiwancheng-icon@2x.png'),
          waitSrc: require('@assets/img/yiwancheng-icon1@2x.png')
        }
      ],
      stepList: [],
      lastTimeDot: require('@assets/img/gaoling-icon@2x.png'),
      activeTimeImg: require('@assets/img/dangqianzhuangtai-icon@2x.png'),
      timeList: [],
      currentPage: 1,
      pageSize: 20,
      receivCurrentPage: 1,
      receivPageSize: 20,
      receivData: {},
      rowData: {},
      receivDataLoading: false,
      tableLoading: false,
      payload: {},
      dialogVisible: false,
      PAY_INFO, // 支付信息
      COLUMNS,
      CONSUME_COLUMNS: [],
      CANCEL_COLUMNS,
      FILE_COLUMNS,
      RECEIVE_COORDINATION, // 收货信息表头
      RECEIVE_COLUMNS, // 收货详情表头
      DELIVERY_ORDER_COLUMNS, // 出库单表头
      SHIPPING_INFORMATION, // 配送信息表头
      STOCK_TYPE,
      logisticsData: [],
      orderDetail: {},
      orderId: '',
      orderCode: '',
      orderDetailId: '',
      orderType: 1,
      busModel: 1,
      activeName: 'first',
      order_tab: [],
      stepData: [],
      stepData_offline: [],
      stepStr_offline: [],
      stockBatchData: [],
      supplierVo: {},
      addressResDto: {},
      orderAppendPOS: [],
      payDetailData: [],
      orderIdReturn: '',
      orderCodeReturn: '',
      orderIdExchange: '',
      orderCodeExchange: '',
      showTableLock: true,
      // 取消产品列表
      cancelTableLoading: false,
      cancelPayload: {},
      filePayload: {
        content: []
      },
      cancelContent: [],
      cancelCurrentPage: 1,
      cancelPageSize: 20,
      returnStutas: '', //  退货状态
      exchangeStutas: '', //  换货状态
      // 消耗产品列表
      consumeTableLoading: false,
      consumePayload: {},
      consumeContent: [],
      consumeCurrentPage: 1,
      consumePageSize: 20,
      // 序列号
      seqNoVoList: [],
      codeDialogVisible: false,
      ACCESSORIES_COLUMNS,
      serial_number: {
        content: []
      },
      serialNumberList: [],
      selectRow: {}
    };
  },
  computed: {
    showOpt() {
      return this.orderDetail.orderStatusName === '已完成';
    }
  },
  created() {
    this.orderId = this.$route.query.orderId;
    this.orderDetailId = this.$route.query.orderDetailId;
    this.orderCode = this.$route.query.orderCode;
    // this.setTime()
    this.CONSUME_COLUMNS = [...this.COLUMNS];
    // 获取步骤条数据
    this.getStepList();
    // 退货/换货按钮展示

    // 根据id获取列表详情
    this.$axios
      .$post(orderCommonQueryOrderInfo, {
        orderId: this.orderId
      })
      .then(res => {
        if (res.code === '0' && res.payload) {
          this.supplierVo = res.payload.supplierVo;
          this.addressResDto = res.payload.addressResDto;
          this.orderAppendPOS = res.payload.orderAppendPOS;
          this.orderDetail = {
            ...res.payload,
            hospitalName: res.payload.contractVo.hospitalName,
            hospitalCode: res.payload.contractVo.hospitalCode
          };
          this.filePayload.content = res.payload.commonFilePOList
          this.orderDetailId = res.payload.orderDetailId;
          this.orderIdReturn = res.payload.orderIdReturn;
          this.orderCodeReturn = res.payload.orderCodeReturn;
          this.orderIdExchange = res.payload.orderIdExchange;
          this.orderCodeExchange = res.payload.orderCodeExchange;
          this.getAppendInfo(res.payload.contractVo);
          this.getCancelList(res.payload.orderDetailId);
          this.getOrderProductList(res.payload.orderDetailId);
          this.findProductSnInfo();
        }
      });
    // 库存配位
    this.$axios
      .$post(stockBatchList, {
        orderId: this.orderId,
        page: 1,
        pageSize: 99999
      })
      .then(res => {
        if (res.code === '0' && res.payload.content) {
          this.stockBatchData = res.payload.content;
        }
      });
  },
  async mounted() {
    const btn = {
      type: 'btn',
      arr: []
    };
    btn.arr.push({
      type: 'primary',
      val: '再来一单',
      handle: this.goAdd
    });
    this.$store.commit('changeLayoutHandle', btn);
    // const obj = {
    //   b: 'b'
    // }
    // obj.a = {
    //   a: 'a',
    //   c: undefined
    // }
    // // obj.a.b = obj
    // console.log(obj, 'obj')
    // let targert = JSON.parse(JSON.stringify(obj))
    // console.log(targert, 'target')
    // function deepClone (val) {
    //   return new Promise(resolve => {
    //     let {port1, port2} = new MessageChannel()
    //     port1.postMessage(val)
    //     port2.onmessage = data => resolve(data)
    //   })
    // }
    // deepClone(obj).then(res => {
    //   console.log(res, 'deep')
    // })
    // await this.getReturnStatus()
    // let arr = [];
    // if(this.returnStutas === 1){
    //   arr.push({type: 'primary', disabled: true, val: '退货中', handle: this.returning})
    // }
    // else if(this.returnStutas === 2){
    //   arr.push({type: 'primary', val: '申请退货', handle: this.applyForReturn})
    // }
    // if(this.exchangeStutas === 1){
    //   arr.push({type: 'primary', disabled: true, val: '换货中', handle: this.exchangeing})
    // }
    // else if(this.exchangeStutas === 2){
    //   arr.push({type: 'primary', val: '申请换货', handle: this.applyForExchange})
    // }
    // let btn = {
    //   type: 'btn',
    //   arr
    // }
    // this.$store.commit('changeLayoutHandle', btn)
  },
  methods: {
    goAdd() {
      this.$router.push({
        path: '/hospital-purchase-order/consume/add',
        query: {
          orderId: this.orderId,
          reAdd: true
        }
      });
    },
    // 序列号 START hospital-purchase-order/consume/add
    // 获取序列号
    findProductSnInfo() {
      this.$axios
        .$post(findProductSnInfo, {
          orderId: this.orderId,
          page: 1,
          pageSize: 9999
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            // eslint-disable-next-line array-callback-return
            (res.payload.content || []).map(s => {
              const newS = s;
              newS.originalFactoryProductCode = s.originalProductCode;
              newS.seqNo = s.snCode || '';
            });
            this.serialNumberList = res.payload.content || [];
          }
        });
    },
    // 打开序列号弹窗
    openSerialNumber(row) {
      this.selectRow = row;
      this.serial_number.content = this.serialNumberList.filter(
        _ => _.orderProductId === row.orderProductId
      );
      this.codeDialogVisible = true;
    },
    // 添加序列号
    // eslint-disable-next-line consistent-return
    addSerialNumber() {
      let next = true;
      let err = '';
      this.serial_number.content.forEach(item => {
        if (!item.snCode) {
          if (next) {
            err = '序列号不能为空，请添加序列号';
            next = false;
          }
        }
        if (!item.productCount) {
          if (next) {
            err = '数量不能为空，请添加数量';
            next = false;
          }
        }
      });
      if (this.serial_number.content.length >= this.selectRow.productCount ) {
        if (next) {
          err = '序列号行数不能大于产品消耗数量';
          next = false;
        }
      }
      if (!next) {
        return this.$message({
          type: 'warning',
          message: err
        });
      }
      const staticOtherItemData = {
        snCode: '', // 序列号
        productCount: '' // 数量
      };
      this.serial_number.content.unshift(staticOtherItemData);
    },
    // 删除一行
    removeCurOtherItem(scope) {
      this.$confirm('确定要删除该序列号吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'delete-code__alert'
      })
        .then(() => {
          this.serial_number.content.splice(scope.$index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    onSaveSerialNumber() {
      // consumePayload.content
      // payload.content
      let dataList = this.payload.content;
      if (this.orderDetail.orderStatusName === '已完成') {
        dataList = this.consumePayload.content;
      }
      const sendList = [];
      dataList.forEach(item => {
        const OBJ = {
          orderProductId: item.orderProductId,
          productCode: item.productCode,
          originalProductCode: item.originalProductCode,
          productName: item.productNameCN,
          batchNo: item.batchNo,
          orderCode: this.orderCode,
          orderId: this.orderId,
          productCount: item.productCount,
          productSnVOList: []
        };
        let serialNumberList = this.serialNumberList.filter(
          _ => _.orderProductId === item.orderProductId
        );
        if (item.orderProductId === this.selectRow.orderProductId) {
          serialNumberList = this.serial_number.content;
        }
        // eslint-disable-next-line no-shadow
        serialNumberList.forEach(item => {
          item.productCount &&
            OBJ.productSnVOList.push({
              productCount: item.productCount,
              snCode: item.snCode
            });
        });
        sendList.push(OBJ);
      });
      const url =
        '/m-mall-center/api/v1/common/MOrderProductSn/saveProductSnList';
      this.$axios.$post(url, sendList).then(() => {
        this.$message({
          message: '序列号保存成功',
          type: 'success'
        });
        // this.findProductSnInfo();
        this.codeDialogVisible = false;
      }).finally(() => {
        this.findProductSnInfo();
      });
    },
    // 序列号 END
    // 退货/换货按钮展示
    getReturnStatus() {
      const params = {
        orderCode: this.orderCode
      };
      return this.$axios.$post(returnStatus, params).then(res => {
        if (res.code === '0') {
          this.returnStutas = res.payload.returnStutas;
          this.exchangeStutas = res.payload.exchangeStutas;
        }
        return Promise.resolve(res);
      });
    },
    // 附加信息转译
    getAppendInfo(obj) {
      this.$axios
        .$post(orderGetAppendInfo, {
          productLineCode: obj.productLineCode,
          vendorNum: obj.supplierCode,
          busModel: 1,
          page: 1,
          pageSize: 9999
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.orderAppendPOS.forEach(item => {
              res.payload.forEach(it => {
                if (item.attributeName === it.attributeName) {
                  const list = it.valueRange ? JSON.parse(it.valueRange) : [];
                  list.forEach(val => {
                    if (val.value === item.attributeValue) {
                      const newItem = item;
                      newItem.attributeValue = val.label;
                    }
                  });
                }
              });
            });
          }
        });
    },
    // 获取两个状态流转接口
    getStepList() {
      this.stepList = [];
      this.$axios
        .$post(orderCommonFindOrderStatus, {
          orderId: this.orderId
        })
        .then(res => {
          if (res.code === '0' && res.payload.orderStatusInfoVO) {
            const list = res.payload.orderStatusInfoVO;
            // 利用find返回true停止遍历的特性
            list.find((item, index) => {
              Object.assign(this.STEP_LIST[index], item);
              this.stepList.push(this.STEP_LIST[index]);
              return item.name === '已取消';
            });
            const index = this.stepList.findIndex(item => item.status === '0');
            this.activeStatus =
              index === -1 ? this.stepList.length - 1 : index - 1;
          } else {
            this.stepList = [];
          }
        })
        .catch(() => {
          this.stepList = [];
        });
      // this.$axios
      //   .$post(commerceGetOrderFlow, {
      //     orderId: this.orderId
      //   })
      //   .then(res => {
      //     if (res.code === '0' && res.payload) {
      //       const list = res.payload;
      //       this.timeList = list;
      //     } else {
      //       this.timeList = [];
      //     }
      //   })
      //   .catch(() => {
      //     this.timeList = [];
      //   });
      // this.$axios.$post(findStockStatus, {
      //   orderId: this.orderId
      // }).then(res => {
      //   if (res.code === '0' && res.payload) {
      //     let data = res.payload.orderStatusInfoVO
      //     let arr = []
      //     let newArr = []
      //     data.map(item => {
      //       if (Number(item.lineNum) === 1) {
      //         arr.push(item)
      //       } else {
      //         newArr.push(item)
      //       }
      //     })
      //     arr.sort(function (a, b) {
      //       return a.orderStatus - b.orderStatus
      //     });
      //     this.stepData_offline.push(arr)
      //     if (newArr.length) {
      //       let num = newArr.length / 2
      //       for (let i = 1; i <= num; i++) {
      //         let itemArr = []
      //         newArr.map(item => {
      //           if (Number(item.lineNum) === i + 1) {
      //             itemArr.push(item)
      //           }
      //         })
      //         itemArr.sort(function (a, b) {
      //           return a.orderStatus - b.orderStatus
      //         });
      //         this.stepData_offline.push(itemArr)
      //       }
      //     }
      //     let str = res.payload.remark ? res.payload.remark.split(',') : []
      //     str.map(item => {
      //       if (this.STOCK_TYPE[item]) {
      //         this.stepStr_offline.push(this.STOCK_TYPE[item])
      //       }
      //     })
      //   }
      // })
    },
    // 表格添加高亮
    // eslint-disable-next-line consistent-return
    tableRowClassName({ row }) {
      if (row.shortSupplyCount) {
        // if (row.productCount > row.confirmCount) {
        return 'bgHeight';
        // }
      }
    },
    // 消耗表格
    async getOrderProductList() {
      this.consumeTableLoading = true;
      this.$axios
        .$post(orderPageList, {
          orderDetailId: this.orderDetailId,
          page: this.consumeCurrentPage,
          pageSize: this.consumePageSize
        })
        .then(res => {
          this.getList();
          if (this.orderDetail.busModel === '57') {
            const OBJ = {
              width: '100',
              prop: 'opt',
              label: '操作',
              fixed: 'right',
              align: 'center'
            };
            this.setColumns('CONSUME_COLUMNS', 'opt', OBJ);
          }
          this.consumePayload = res.payload;
          this.consumeTableLoading = false;
        });
    },
    // 订单详情采购产品分页列表分页器
    reloadConsumeProductData(val) {
      this.consumeCurrentPage = val.number;
      this.consumePageSize = val.size;
      this.getOrderProductList();
    },
    // 订单详情采购产品分页列表
    getList() {
      this.tableLoading = true;
      this.$axios
        .$post(orderProductList, {
          orderDetailId: this.orderDetailId,
          page: this.currentPage,
          pageSize: this.pageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.COLUMNS[this.COLUMNS.length - 1].prop === 'opt'
            && this.COLUMNS.splice(this.COLUMNS.length - 1, 1)
            if (this.activeStatus === 0 || this.activeStatus === 1) {
              let haveErr = false;
              res.payload.content.forEach(item => {
                item.errorMessage && (haveErr = true);
              });
              if (haveErr) {
                const OBJ = {
                  width: '100',
                  prop: 'errorMessage',
                  label: '异常信息',
                  'show-overflow-tooltip': true
                };
                this.setColumns('COLUMNS', 'errorMessage', OBJ);
                this.setColumns('CONSUME_COLUMNS', 'errorMessage', OBJ);
              } else {
                this.COLUMNS[this.COLUMNS.length - 1].prop === 'errorMessage'
                && this.COLUMNS.splice(this.COLUMNS.length - 1, 1)
                this.CONSUME_COLUMNS[this.CONSUME_COLUMNS.length - 1].prop === 'errorMessage'
                && this.CONSUME_COLUMNS.splice(this.CONSUME_COLUMNS.length - 1, 1)
              }
              this.payload = res.payload;
            }
            if (this.orderDetail.busModel === '57') {
              const DataSources = res.payload.content.filter(item => !item.dataSources);
              if (DataSources.length) {
                const OBJ = {
                  width: '100',
                  prop: 'opt',
                  label: '操作',
                  fixed: 'right',
                  align: 'center'
                };
                if (this.orderDetail.orderStatus === 7) {
                  this.setColumns('CONSUME_COLUMNS', 'opt', OBJ);
                } else {
                  this.setColumns('COLUMNS', 'opt', OBJ);
                }
              }
            }
            this.payload = res.payload;
          }
          this.tableLoading = false;
          this.showTableLock = false;
        });
    },
    setColumns(columns, key, obj) {
      !this[columns].filter(_ => _.prop === key).length &&
        this[columns].push(obj);
    },
    // 订单详情采购产品分页列表分页器
    reloadProductData(val) {
      this.currentPage = val.number;
      this.pageSize = val.size;
      this.getList();
    },
    // 取消产品分页器
    cancelReloadProductData(val) {
      this.cancelCurrentPage = val.number;
      this.cancelPageSize = val.size;
      this.getCancelList();
    },
    // 获取取消的产品列表
    getCancelList() {
      this.cancelTableLoading = true;
      this.$axios
        .$post(orderCancelProductList, {
          orderDetailId: this.orderDetailId,
          page: this.cancelCurrentPage,
          pageSize: this.cancelPageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload.content) {
            this.cancelPayload = res.payload;
            this.cancelContent = res.payload.content;
          }
          this.cancelTableLoading = false;
        });
    },
    // 底部tab切换调用不同接口
    handleClick(tab) {
      if (tab.name === 'fourth') {
        this.getOrderDeliverList();
      }
      if (tab.name === 'second') {
        this.getPayment();
      }
      if (tab.name === 'third') {
        this.getLogistics();
      }
    },
    // 支付信息
    getPayment() {
      this.$axios
        .$get(`${findPaymentByOrderId}?orderId=${this.orderId}`)
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.payDetailData = [res.payload];
          }
        });
    },
    // 配送信息
    getLogistics() {
      this.$axios
        .$post(getOrderLogistics, {
          orderCode: this.orderDetail.orderCode
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.logisticsData = res.payload;
          }
        });
    },
    // 收货信息列表
    getOrderDeliverList() {
      this.$axios
        .$get(`${getOrderDeliverList}?orderCode=${this.orderDetail.orderCode}`)
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.order_tab = res.payload;
          }
        });
    },
    showLog(row) {
      this.dialogVisible = true;
      this.rowData = row;
      this.getReceivList();
    },
    // 收货信息-详情列表分页器
    reloadReceiv(val) {
      this.receivCurrentPage = val.number;
      this.receivPageSize = val.size;
      this.getReceivList();
    },
    // 收货信息-详情列表
    getReceivList() {
      this.receivDataLoading = true;
      this.$axios
        .$post(getOrderDeliverDetailList, {
          deliverCode: this.rowData.deliverCode,
          page: this.receivCurrentPage,
          pageSize: this.receivPageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.receivData = res.payload;
          }
          this.receivDataLoading = false;
        });
    },
    // 退货中页面跳转
    returning() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdReturn,
          orderCode: this.orderCodeReturn
        }
      });
    },
    // 申请退货页面跳转
    applyForReturn() {
      this.$router.push({
        path: '/purchase-order/wholesale/list/return',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      });
    },
    // 换货中页面跳转
    exchangeing() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdExchange,
          orderCode: this.orderCodeExchange
        }
      });
    },
    // 申请换货页面跳转
    applyForExchange() {
      this.$router.push({
        path: '/purchase-order/wholesale/list/exchange',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      });
    }
  }
};
